import re
from config import ENDING_PUNCTUATION_MAP, CHINESE_QUOTES, ABBREVIATIONS
from deepseek_api import deepseek_resplit_paragraph

def validate_paragraph_endings(para_cn, para_en, para_idx):
    """校验单个中英文段落的句子结束符号匹配情况"""
    # 提取中文段落结束符号序列
    ch_endings = []
    ch_sentences = []
    current_sentence = ""

    for char in para_cn:
        current_sentence += char
        if char in ENDING_PUNCTUATION_MAP:
            ch_endings.append(ENDING_PUNCTUATION_MAP[char])
            ch_sentences.append(current_sentence.strip())
            current_sentence = ""

    if current_sentence:
        ch_sentences.append(current_sentence.strip())

    # 提取英文段落结束符号序列
    en_endings = []
    en_sentences = []
    current_sentence = ""

    words = re.split(r'(\s+)', para_en)  # 保留空格
    for i, word in enumerate(words):
        current_sentence += word
        stripped_word = word.strip()

        if not stripped_word:
            continue

        # 检查结束符+引号结尾的情况
        if len(stripped_word) >= 2 and stripped_word[-1] in CHINESE_QUOTES and stripped_word[
            -2] in ENDING_PUNCTUATION_MAP.values():
            ending_char = stripped_word[-2]
            clean_word = re.sub(r'[^\w]', '', stripped_word[:-2]).lower()
            is_abbreviation = clean_word in ABBREVIATIONS

            # 获取下一个非空字符
            next_char = None
            j = i + 1
            while j < len(words) and next_char is None:
                next_word = words[j].strip()
                if next_word:
                    start_idx = 0
                    while start_idx < len(next_word) and next_word[start_idx] in CHINESE_QUOTES:
                        start_idx += 1
                    if start_idx < len(next_word):
                        next_char = next_word[start_idx]
                j += 1

            if (not is_abbreviation and
                    (next_char is None or not next_char.isalpha() or not next_char.islower())):
                en_endings.append(ending_char)
                en_sentences.append(current_sentence.strip())
                current_sentence = ""

        # 检查常规结束符
        elif stripped_word[-1] in ENDING_PUNCTUATION_MAP.values():
            clean_word = re.sub(r'[^\w]', '', stripped_word).lower()
            is_abbreviation = clean_word in ABBREVIATIONS

            # 获取下一个非空字符
            next_char = None
            j = i + 1
            while j < len(words) and next_char is None:
                next_word = words[j].strip()
                if next_word:
                    start_idx = 0
                    while start_idx < len(next_word) and next_word[start_idx] in CHINESE_QUOTES:
                        start_idx += 1
                    if start_idx < len(next_word):
                        next_char = next_word[start_idx]
                j += 1

            if (not is_abbreviation and
                    (next_char is None or not next_char.isalpha() or not next_char.islower())):
                en_endings.append(stripped_word[-1])
                en_sentences.append(current_sentence.strip())
                current_sentence = ""

    if current_sentence:
        en_sentences.append(current_sentence.strip())

    # 检查结束符号是否匹配
    if len(ch_endings) != len(en_endings):
        print(f"❌ 段落 {para_idx + 1} 结束符号数量不匹配: 中文 {len(ch_endings)} 个, 英文 {len(en_endings)} 个")
        return False

    for i, (ch_end, en_end) in enumerate(zip(ch_endings, en_endings)):
        if ch_end != en_end:
            print(f"❌ 段落 {para_idx + 1} 位置 {i + 1}: 中文结束符 '{ch_end}' ≠ 英文结束符 '{en_end}'")
            return False

    print(f"✅ 段落 {para_idx + 1} 结束符号匹配")
    return True


def validate_with_resplit(para_cn, para_en, para_idx):
    """使用DeepSeek重新分句后再次验证结束符号"""
    print(f"尝试重新分句段落 {para_idx + 1}...")

    # 重新分句中英文段落
    resplit_cn = deepseek_resplit_paragraph(para_cn, "chinese")
    resplit_en = deepseek_resplit_paragraph(para_en, "english")

    # 再次验证结束符号
    return validate_paragraph_endings(resplit_cn, resplit_en, para_idx)